package com.kyle.redpacket.controller;

import com.kyle.redpacket.dao.entity.RedPacket;
import com.kyle.redpacket.dao.entity.RedRecord;
import com.kyle.redpacket.dto.result.Result;
import com.kyle.redpacket.dto.result.ResultEnum;
import com.kyle.redpacket.dto.result.ResultException;
import com.kyle.redpacket.service.IRedPacketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.atomic.AtomicLong;


@RestController
@Slf4j
public class RedPacketController {

    public static final AtomicLong longX = new AtomicLong(Long.MIN_VALUE);
    //注入红包业务逻辑处理接口服务
    @Autowired
    private IRedPacketService redPacketService;

    /**
     * 发红包请求，请求方法为POST，请求参数采用JSON格式提交
     */
    @PostMapping(value = "/hand/out", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Result<?> handOut(@Validated @RequestBody RedPacket dto, BindingResult result) throws Exception {
        //参数校验
        if (result.hasErrors()) {
            return Result.isOk();
        }
        //核心业务逻辑非服务，最终返回全局唯一标识串
        RedPacket redPacket = redPacketService.handOut(dto);
        //将红包全局唯一标识串返回前段
        return Result.isOk(redPacket);
    }

    /**
     * 抢
     */
    @GetMapping(value = "/rob")
    public Result<?> rob(
            @RequestParam Long userId,
            @RequestParam String redId
                        ) throws Exception {
        //为了偷懒，按顺序生成抢红包用户的id
        return rob(userId, redId, longX.getAndIncrement());
    }

    public Result<?> rob(
            @RequestParam Long userId,
            @RequestParam String redId,
            @RequestParam Long robUserId) throws Exception {
        /**
         * 调用红包业务逻辑处理接口中的抢红包方法，最终返回敲到的红包的金额
         * 单位为源（不为null是表示抢到了，否则代表抢光了）
         */
        RedRecord result = redPacketService.rob(userId, robUserId, redId);
        if (result != null) {
            //将抢到的红包金额返回到前端
            return Result.isOk(result);
        }
        else {
            //没有抢到红包，即已经被抢完了
            throw new ResultException(ResultEnum.RUN_OUT_OF_MONEY);
        }
    }
}
























